<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #selectRoleNames="{ model, field }">
        <a-select mode="multiple" :options="roleData" v-model:value="model[field]" allowClear />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './users.data';
  import {
    postUsers,
    putUsers,
    getUsersDepts,
    getUsersRoleList,
    getDeptAllList,
    getRoleAllList,
  } from '/@/api/sys/system';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import { Select } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm, ASelect: Select },
    emits: ['success', 'register'],
    setup() {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const rowId = ref('');
      const roleData = ref<any>([]);
      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        //获取部门数据
        const treeData = listToTree(await getDeptAllList(), { id: 'id', pid: 'parentId' });
        //获取角色数据
        let roleListData = (await getRoleAllList()).items;
        if (roleListData) {
          roleData.value = [];
          roleListData.forEach(function (item) {
            roleData.value.push({ label: item.name, value: item.name });
          });
        }
        updateSchema([
          {
            field: 'password',
            required: !isUpdate.value,
          },
          {
            field: 'deptId',
            componentProps: { treeData },
          },
          {
            field: 'userName',
            dynamicDisabled: data.record?.userName == 'admin',
          },
        ]);

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          //获取当前用户对应的角色列表
          const current_user_rolelist = await getUsersRoleList(rowId.value);
          data.record.roleNames = current_user_rolelist.items.map(function (n) {
            return n.name;
          });
          //获取当前用户对应的部门列表
          const current_user_depts = await getUsersDepts(rowId.value);
          data.record.deptId = current_user_depts.organizationUnitId;
          setFieldsValue({ ...data.record });
        }
        //roleData.value =  as any; 
      });
      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const model_data = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api 
          if (isUpdate.value) {
            await putUsers(
              rowId.value,
              Object.assign({ extraProperties: { deptId: model_data['deptId'] } }, model_data),
            ).then(() => {
               createMessage.success('修改成功!');
            });
          } else {
            await postUsers(
              Object.assign({ extraProperties: { deptId: model_data['deptId'] } }, model_data),
            ).then(() => { 
              createMessage.success('创建成功!');
            });
          }
          closeModal();
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, roleData };
    },
  });
</script>
